<?php


namespace app\admin\controller;

use app\admin\model\Role as Model;
use support\annotation\NoNeedLogin;
use support\annotation\NoNeedRight;
use support\Request;
use support\util\TreeArray;
use support\View;

class Role extends BaseController
{
    protected $model = Model::class;

    protected $preViewName = 'role';

    public function index(Request $request)
    {
        if ($request->expectsJson()) {
            $list = Model::query()->get();
            $this->success("获取成功", $list);
        }
        return $this->view('index');
    }

    public function show(Request $request)
    {
        $id = $request->get('id', null);
        if ($id !== null) {
            $row = Model::query()->find($id);
            View::assign('row', $row);
        }

        return $this->view('show', [
            'pid' => $request->get('pid', isset($row) ? $row->pid : $request->get('pid', 0)),
            'statusList' => Model::getStatusList(),
            'treeList' => Model::getTreeSelect()
        ]);
    }

    /**
     * @NoNeedRight()
     */
    public function select() {
        $this->success("获取成功", array_merge([['id' =>0, 'nickname' => '顶级角色', 'pid' => 0]], Model::getTreeSelect()));
    }

    protected function store(Request $request)
    {
        $form = $request->post('form');
        if (isset($form['id'])) {
            $row = Model::query()->find($form['id']);
            if (!$row) {
                $this->error('未找到!');
            }
            unset($form['id']);
        }else {
            $row = new $this->model();
        }
        if (isset($form['pid']) && $form['pid'] != 0) {
            $prow = Model::query()->find($form['pid']);
            if ($prow) {
                $form['pids'] = $prow->pids . ',' . $prow->id;
            }
        }
        $row->fill($form);
        $row->save();
        // 同步菜单权限
        $row->menus()->sync($form['menusids']);
        $this->success("操作成功!");
    }

    public function authselect(Request $request) {
        $id = $request->get('id', null);
        $selectIds = collect();
        if ($id) {
            $row = Model::query()->find($id);
            if ($row) {
                $selectIds = $row->menus()->pluck('id');
            }
        }
        $pid = $request->get('pid');
        if ($pid != 0) {
            /**
             * @var $parentRole Model
             */
            $parentRole = Model::query()->find($pid);
            if (!$parentRole) {
                $this->error("未找到上级角色!");
            }
            $menuColl = $parentRole->menus()->get();
        } else {
            $menuColl = \app\admin\model\Menu::get();
        }
        $menuArr = $menuColl->toArray();
        foreach ($menuArr as &$menuValue) {
            $menuValue['checked'] = in_array($menuValue['id'], $selectIds->toArray());
        }
        $tree = TreeArray::instance();
        $tree->init($menuArr);
        $this->success("", $tree->getTreeArray(0));
    }
}
